/* entity */
import LoginUser from '@model/entity/LoginUser/LoginUser'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
/* model */
import { ChartUser } from '@model/param/out/Chart'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, defineComponent, Ref, ref, onMounted, computed, watch } from 'vue'
import { CommonComponentInstance } from '@model/VC'
/* util */
import { isOpenData } from '@src/util/platform'
import _ from 'lodash';
// API
import * as ReportApi from '@src/api/ReportApi'

interface ChartUserSelectSetupState {
  // 人员选择框变化事件
  handlerUserChange: (value: string[]) => void;
  // 图表人员列表
  userList: Ref<ChartUser[]>;
}

interface LoadmoreOptions {
  // 是否禁用
  disabled: boolean,
  // 回调函数
  callback: Function,
  // 触发距离
  distance: number
}

enum ChartUserSelectEventEnum {
  Input = 'input'
}

export type ChartUserSelectProps = {
  // 人员值数组
  value: string[];
  // 部门值数组
  tags: string[];
}

// 人员列表参数
export type ChartUserParams = {
  state: string,
  teamId: string
}
export type ChartUserSelectInstance = ComponentInstance & ChartUserSelectSetupState
export type ChartUserSelectVM = ComponentRenderProxy<ChartUserSelectProps> & CommonComponentInstance

export type ChartSelectUser = {
  label: string;
  value: string;
}


export default defineComponent<ChartUserSelectProps, ChartUserSelectSetupState>({
  name: ComponentNameEnum.ChartUserSelect,
  props: {
    value: {
      type: Array,
      default: () => []
    },
    tags: {
      type: Array,
      default: () => []
    }
  },
  setup(props: ChartUserSelectProps, { emit }) {

    // 人员列表数据
    let userList: Ref<ChartSelectUser[]> = ref([])
    
    let params: Ref<ChartUserParams> = computed(() => { 
      return {
        state: '',
        teamId: props.tags.join(',')
      }
    })
    
    const tags: Ref<string[]> = computed(() => {
      return props.tags
    })

    // watch(tags,(n,o) => {
    //   fetchChartUser()
    // })
    
    /** 
     * @description 人员选择框变化事件
    */
    const handlerUserChange = (value: string[]) => {
      emit(ChartUserSelectEventEnum.Input, value)
    }

    /** 
     * @description 获取人员数据
    */
    const loading = ref(false);
    const pageNum = ref(1);
    const userName = ref('');
    const total = ref(0);
    const fetchChartUser = async (queryAll: Boolean = true) => {
      try{
        loading.value = true;
        const { code, data, msg } = await ReportApi.getPcTeamUser({
          queryAll, // 是否展示已删除
          userName: userName.value,
          pageNum: pageNum.value,
          pageSize: 10
        })

        loading.value = false;
        total.value = data.totalCount;
        userList.value = userList.value.concat(data.baseUserDTOList);
      }catch(err){
        console.log('fetchChartUser', err);
      }
    }

    // 人员搜索 start
    const remoteMethod = (query: string)=>{
      pageNum.value = 1;
      userName.value = query;
      userList.value = []
      fetchChartUser();
    }
    const visibleHandler = (visible: boolean)=>{
      if(visible) return fetchChartUser();
    }

    // 人员分页
    const loadmore = _.debounce(() => {
      if(userList.value.length === total.value) return;

      pageNum.value++;
      fetchChartUser();
    }, 50)

    const loadmoreOptions: LoadmoreOptions = {
      disabled: false,
      callback: loadmore,
      distance: 10
    }
    // 人员搜索 end

    onMounted(() => {
      fetchChartUser();
    })

    return {
      userList,
      loading,
      handlerUserChange,
      remoteMethod,
      visibleHandler,
      loadmoreOptions,
    }
  },
  render() {
    const openMultipleSlot = (scope: { item: LoginUser }) => {
      const user = scope.item
      
      if (isOpenData && user.staffId) {
        return <open-data type="userName" openid={user.staffId}></open-data>
      }
      
      return user?.displayName ?? ''
    }
    
    const defaultOptionSlot = (user: ChartUser ) => {
      return <open-data type='userName' openid={user.staffId}></open-data>
    }
    
    return (
      <el-select
        value={this.value}
        filterable
        remote
        multiple
        clearable
        collapse-tags
        v-el-select-loadmore={this.loadmoreOptions}
        placeholder="请选择人员"
        remote-method={this.remoteMethod}
        onInput={this.handlerUserChange}
        scopedSlots={{
          multiple: openMultipleSlot
        }}
      >
        {
          this.userList && this.userList.map((user: ChartUser) => {
            return (
              <el-option
                key={user.userId}
                label={user.displayName}
                value={user.userId}
                origin={user}
              >
                { isOpenData && defaultOptionSlot(user) }
              </el-option>
            )
          })
        }
      </el-select>
    )
  }
})
